package com.zaofan.mobile.controller;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zaofan.bean.DynamicDTO;
import com.zaofan.exception.ServiceException;
import com.zaofan.service.DynamicService;
import com.zaofan.utils.JsonUtils;
import com.zaofan.utils.WebUtils;

/**
 * 动态发布接口
 *
 */
@WebServlet("/mobile/dynamicAddIos")
public class DynamicIosAddController extends HttpServlet {

	private static final long serialVersionUID = 5884947841079014459L;
	private DynamicService dynamicService = new DynamicService();
	private static List<String> allowType = Arrays.asList("image/bmp","image/png","image/gif","image/jpg","image/jpeg","image/pjpeg");  
	private static List<String> allowSuffix = Arrays.asList(".png",".gif",".jpg",".jpeg",".pjpeg"); 
	private static Map<String, String> mFileTypes = new HashMap<String, String>();
	private static final Logger logger = LoggerFactory.getLogger(DynamicIosAddController.class);
	
	static {
		mFileTypes.put("FFD8FFE0", ".jpg");
	    mFileTypes.put("89504E47", ".png");
	    mFileTypes.put("47494638", ".gif");
	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		add(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	/**
	 * 发布动态
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			DynamicDTO dto;
			if (ServletFileUpload.isMultipartContent(request)) {
				dto = dealAppAddDynamic(request);
			} else {
				dto = WebUtils.write2bean(request, DynamicDTO.class);
			}
			dynamicService.userCreateDynamic(dto);
			JsonUtils.writeSuccessJson("动态发布成功", "", response);
			return;
		} catch (ServiceException e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson(e.getMessage(), response);
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("发布失败", response);
		}
		JsonUtils.writeBeanFailJson("发布失败!!", response);
	}

	private DynamicDTO dealAppAddDynamic(HttpServletRequest request) {
		DynamicDTO dto = new DynamicDTO();
		String images = "";
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("iso8859-1");
		String random = new Random().nextInt() + "";
		try {
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					String value = item.getString();
					value = new String(value.getBytes("iso8859-1"), "utf-8");
					String key = item.getFieldName();
					BeanUtils.setProperty(dto, key, value);
					System.out.println(key + " = " + value);
				} else {
					if (!allowType.contains(item.getContentType()) || !allowSuffix.contains(item.getName().substring(item.getName().lastIndexOf(".")).toLowerCase())) {
						logger.info("item.getContentType: {}, item.getName: {}", item.getContentType(), item.getName());
						return dto;
					}
					InputStream in = item.getInputStream();
					String path = WebUtils.makeDir(getServletContext().getRealPath("/user_image"),
							new StringBuilder(String.valueOf(random)).toString()) + "/" + WebUtils.getUUID() + "_"
							+ random + item.getName().substring(item.getName().lastIndexOf("."));
					FileOutputStream out = new FileOutputStream(
							getServletContext().getRealPath("/user_image") + "/" + path);
					BufferedOutputStream bos = new BufferedOutputStream(out);
					int len = 0;
					byte[] buff = new byte[1024];
					byte[] type = new byte[4];
					len = in.read(type);
					if (mFileTypes.containsKey(bytesToHexString(type))) {
						bos.write(type, 0, len);
					} else {
						logger.info("文件类型不是图片：{}", item.getName());
						bos.close();
						return dto;
					}
					while ((len = in.read(buff)) != -1) {
						bos.write(buff, 0, len);
					}
					bos.close();
					images += "/user_image/" + path + ",";
				}
			}
			if (images.length() > 0) {
				images = images.substring(0, images.length() - 1);
			}
			dto.setImage(images);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dto;
	}
	 private static String bytesToHexString(byte[] src) {
	        StringBuilder builder = new StringBuilder();
	        if (src == null || src.length <= 0) {
	            return null;
	        }
	        String hv;
	        for (int i = 0; i < src.length; i++) {
	            // 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式，并转换为大写
	            hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
	            if (hv.length() < 2) {
	                builder.append(0);
	            }
	            builder.append(hv);
	        }
	         
	        System.out.println("获取文件头信息:"+builder.toString());
	         
	        return builder.toString();
	    }
}
